package com.agrm.upload.controller;

import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.upload.utils.AliOssUtil;
import com.alibaba.nacos.api.model.v2.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("api/v1/upload")
public class UploadController {


    @Autowired
    private AliOssUtil aliOssUtil;


    @PostMapping("picture")
    public ResponseResult uploadPicture(@RequestBody MultipartFile file) {
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截去文件的后缀名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            //获取当前年月作为文件夹路径
            String dir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));

            //UUID生成新的文件名
            String newFilename = dir + "/" + UUID.randomUUID() + extension;

            String filePath = aliOssUtil.upload(file.getBytes(), newFilename);

            return ResponseResult.okResult(filePath);
        } catch (IOException e) {
            return ResponseResult.errorResult(500, "上传失败");
        }
    }

}
